#!/usr/bin/python3
# coding=utf-8

# Copyright (c) 2025 Huawei Technologies Co., Ltd.
# This file is a part of the CANN Open Software.
# Licensed under CANN Open Software License Agreement Version 1.0 (the "License").
# Please refer to the License for details. You may not use this file except in compliance with the License.
# THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED,
# INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT, MERCHANTABILITY, OR FITNESS FOR A PARTICULAR PURPOSE.
# See LICENSE in the root of the software repository for the full text of the License.
# ======================================================================================================================
import os
import sys
import csv
import logging
import subprocess
import shlex


logging.basicConfig(level=logging.INFO)


def get_file_work_dir():
    current_path = os.getcwd()
    file_work_dir = os.path.dirname(current_path)
    return file_work_dir


def get_case_list():
    current_path = os.getcwd()
    case_dir = os.path.join(os.path.dirname(current_path), "testcase")
    if not os.path.exists(case_dir):
        logging.info("[ERROR] file path %s not exist!" % (case_dir))
        return None

    case_list = []
    for file_name in os.listdir(case_dir):
        if not file_name.endswith(".csv"):
            continue

        abs_file_name = os.path.join(case_dir, file_name)
        with open(abs_file_name, mode='r', encoding='utf-8') as file:
            csv_reader = csv.reader(file)
            for row in csv_reader:
                item_list = []
                item_list.append(int(row[0].lstrip("\ufeff")))
                item_list.append(row[1])
                item_list.append(int(row[2]))
                item_list.append(int(row[3]))
                item_list.append(int(row[4]))
                if len(row) > 5:
                    item_list.append(int(row[5]))
                else:
                    item_list.append(1)
                case_list.append(item_list)
    return case_list


def find_prof_file(perf_dir):
    for root, _, files in os.walk(perf_dir):
        for file in files:
            if file.startswith("OpBasicInfo"): # msprof op_summary_* / msprof op OpBasicInfo*
                return os.path.join(root, file)
    return ""


def get_perf_task_duration(prof_output_dir):
    task_duration = 0
    prof_file = find_prof_file(prof_output_dir)

    try:
        with open(prof_file, mode='r', encoding='utf-8') as file:
            csv_reader = csv.DictReader(file)
            for row in csv_reader:
                task_duration = row["Task Duration(us)"]
    except FileNotFoundError:
        logging.info("[WARNNING] can't find profiling file!")
        return 0

    return task_duration


def clear_file_cache(file_work_dir):
    rm_files = file_work_dir + "/input/*"
    os.system("rm -rf " + rm_files)
    rm_files = file_work_dir + "/output/*.txt"
    os.system("rm -rf " + rm_files)
    rm_files = file_work_dir + "/output/*.bin"
    os.system("rm -rf " + rm_files)
    rm_files = file_work_dir + "/bin/prof_out/*"
    os.system("rm -rf " + rm_files)
    rm_files = file_work_dir + "/bin/sim_out/*"
    os.system("rm -rf " + rm_files)


def get_process_case_cmd(kernel_name, params_str, is_perf, run_mode):
    if is_perf:
        cmd = f"msprof op --application=\"./{kernel_name} {params_str}\" --output=./prof_out"
    elif run_mode == "sim":
        cmd = f"msprof op simulator --application=\"./{kernel_name} {params_str}\" --output=./sim_out"
    else:
        cmd = f"./{kernel_name} {params_str}"
    return shlex.split(cmd)